package proj.server;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.List;

import proj.common.Config;
import proj.common.Novel;
import proj.common.Request;
import proj.common.Response;

public class MyServer {
	public static void main(String[] args) {
		try {
			// ServerSocket st = new ServerSocket(8888);
			ServerSocket st = new ServerSocket(Config.getPort());
			while (true) {
				Socket s = st.accept();
				new ObjectThread(s).start();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

class ObjectThread extends Thread {
	private Socket s;

	private NovelManager novelManager = new NovelManager();

	public ObjectThread(Socket s) {
		this.s = s;
	}

	// 获得小说分类
	public Response getNovelBytType(Request req) {
		// return new Response(false, "没有实现");
		List<Novel> list = novelManager.getNovels();
		Response resp = new Response(true);
		resp.put("novels", list);
		return resp;
	}

	public Response login(Request req) {
		Response resp = new Response();

		String name = (String) req.get("userName");
		String pass = (String) req.get("userpass");

		if ("jim".equals(name) && "1234".equals(pass)) {
			resp.setSucess(true);
			resp.setMsg("login successful");
		} else {
			resp.setSucess(false);
			resp.setMsg("错误的用户名或者密码");
		}
		return resp;
	}

	// 文件下载
	public Response download(Request req) {
		String fileName = (String) req.get("fileName");
		String fileFloder = "D:\\我的文档\\My Pictures";
		File f = new File(fileFloder, fileName);
		if (!f.exists()) {
			return new Response(false, "文件不存在");
		}
		String name = f.getName();
		if (!(name.endsWith(".jpg") || name.endsWith(".gif") || name.endsWith(".png"))) {
			return new Response(false, "文件禁止下载");
		}
		byte b[] = new byte[(int) f.length()];
		try {
			FileInputStream fin = new FileInputStream(f);

			fin.read(b);
			fin.close();
		} catch (IOException e) {
			e.printStackTrace();
			return new Response(false, "文件读取失败：" + e);
		}
		Response resp = new Response(true, "文件" + f.getName() + "读取成功");
		resp.put("fileContent", b);
		return resp;
	}

	// 文件上传
	public Response upload(Request req) {
		Response resp = new Response();
		//
		String fileName = (String) req.get("fileName");
		byte[] b = (byte[]) req.get("fileContent");
		try {
			FileOutputStream fout = new FileOutputStream("E:/java61/" + fileName);
			fout.write(b);
			fout.close();
			resp.setSucess(true);
			resp.setMsg("文件保存到我的电脑上了，文件名是：" + fileName);
		} catch (Exception e) {
			e.printStackTrace();
			resp.setSucess(false);
			resp.setMsg("文件上传失败：" + e);
		}
		return resp;
	}

	// 退出
	public Response logout(Request req) {
		return new Response(true, "同时关闭");
	}

	@Override
	public void run() {
		try {
			System.out.println(s + "连接了。。。");
			OutputStream out = s.getOutputStream();
			InputStream in = s.getInputStream();
			ObjectOutputStream oo = new ObjectOutputStream(out);
			ObjectInputStream oin = new ObjectInputStream(in);
			while (true) {
				// 先获得客户端的请求
				Request req = (Request) oin.readObject();
				Response resp = null;
				Method m = this.getClass().getDeclaredMethod(req.getAction(), Request.class);
				try {
					resp = (Response) m.invoke(this, req);
				} catch (Exception e) {
					resp = new Response();
					resp.setSucess(false);
					resp.setMsg("出现异常：" + e);
				}

				// if (req.getAction().equals("login")) {
				// resp = login(req);
				// } else if (req.getAction().equals("download")) {
				// resp = download(req);
				// } else if (req.getAction().equals("upload")) {
				// resp = upload(req);
				// } else {
				// resp = new Response();
				// resp.setSucess(false);
				// resp.setMsg("没有找到这个功能");
				// }
				oo.writeObject(resp);// 反馈结果
				oo.flush();
				oo.reset();// !!!重置，非常关键

				if ("logout".equals(req.getAction()))
					break;
			}
		} catch (Exception e) {
			// e.printStackTrace();
			System.out.println(s + " error:" + e);
		} finally {
			System.out.println(s + "退出");
		}

	}
}